import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:o2oa_all_platform/pages/home/apps/index.dart';

import '../models/index.dart';
import '../services/index.dart';
import '../utils/index.dart';
import '../widgets/index.dart';
import 'x_attendance_assemble_control.dart';

///
///中心服务
///
class ProgramCenterService extends GetxService {
  static ProgramCenterService get to => Get.find();

  // 内存中放置 后续使用
  AppStyle? _appStyle;

  AppStyle? get appStyle {
    if (_appStyle == null) {
      String style = SharedPreferenceService.to
          .getString(SharedPreferenceService.appStyleSpKey);
      OLogger.d("当前服务器的appStyle: $style");
      if (style.isNotEmpty) {
        _appStyle = AppStyle.fromJson(O2Utils.parseStringToJson(style));
      }
    }
    return _appStyle;
  }

  String baseUrl() {
    var centerUrl = O2ApiManager.instance.getCenterBaseUrl();
    if (centerUrl == null || centerUrl.isEmpty) {
      return '';
    }
    return centerUrl;
  }

  /// 执行脚本
  /// [scriptName] 脚本名称
  /// [body] 传入参数
  Future<dynamic> executeScript(String scriptName,  Map<String, dynamic> body) async {
      try {
      ApiResponse response = await O2HttpClient.instance.post('${baseUrl()}jaxrs/invoke/$scriptName/execute', body);
      if (response.isSuccess()) {
        final value = ScriptExecuteResponse.fromJson(response.data);
        return value.value;
      }
    } catch  (err, stackTrace) {
      OLogger.e('执行脚本失败', err, stackTrace);
    }
    return null;
  }

  ///  连接O2OA center服务器
  Future<bool> loadCenterServerOnline() async {
    var unit = O2ApiManager.instance.o2CloudServer;
    if (unit == null) {
      return false;
    }
    if (baseUrl().isEmpty) {
      return false;
    }
    try {
      var url =
          "${baseUrl()}jaxrs/distribute/webserver/assemble/source/${unit.centerHost}";
      ApiResponse response =
          await O2HttpClient.instance.get(url, needToken: false);
      if (response.data == null) {
        return false;
      }
      var dataJson = json.encode(response.data);
      await O2ApiManager.instance.putCenterServerJson2SP(dataJson);
      return true;
    } catch (err, stackTrace) {
      OLogger.e('连接服务器失败', err, stackTrace);
      return false;
    }
  }

  ///
  /// 在线获取移动app相关的配置
  ///
  Future<AppStyle?> loadCurrentStyle() async {
    try {
      ApiResponse response = await O2HttpClient.instance
          .get('${baseUrl()}jaxrs/appstyle/current/style', needToken: false);
      if (response.isSuccess()) {
        AppStyle appStyle = AppStyle.fromJson(response.data);
        _appStyle = appStyle;
        final needGrey = SharedPreferenceService.to.getBool(SharedPreferenceService.appStyleNeedGreyKey, defaultValue: false);
        final newNeedGrey = appStyle.needGray ?? false;
        if (needGrey != newNeedGrey) {
          OLogger.d('全局黑白的变化 ............');
          await SharedPreferenceService.to.putBool(SharedPreferenceService.appStyleNeedGreyKey, newNeedGrey);
          EventBus().emit(EventBus.greyColorChangeGlobalMsg); // 发送通知 重建 ui
        }
        _storeAppStyle2SP(appStyle);
        OLogger.d("请求完成，获取到appstyle！");
        return appStyle;
      }
    } catch (err, stackTrace) {
      OLogger.e('获取appStyle失败', err, stackTrace);
    }

    return null;
  }

  ///
  /// 把appStyle对象存储存储到sp
  ///
  Future<void> _storeAppStyle2SP(AppStyle appStyle) async {
    String jsonAppStyle = json.encode(appStyle.toJson());
    await SharedPreferenceService.to
        .putString(SharedPreferenceService.appStyleSpKey, jsonAppStyle);
  }

  ///
  /// 原生应用列表
  ///
  List<AppFrontData?> getCurrentNativeAppList() {
    var list = appStyle?.nativeAppList ?? [];
    List<AppFrontData?> ret = list
        .map<AppFrontData?>((e) {
          O2NativeAppEnum? appEnum = _getO2NativeWithKey(e.key);
          if (appEnum == null) {
            return null;
          }
          if (e.enable == false) {
            return null;
          }
          AppFrontData data = AppFrontData(
              name: appEnum.name,
              displayName: e.displayName,
              key: appEnum.key,
              type: O2AppTypeEnum.native,
              nativeEnum: appEnum);
          return data;
        })
        .where((element) => element != null)
        .toList();
    // && !AttendanceAssembleControlService.to.isV2() 暂时显示旧版打卡 后面版本将隐藏旧打卡
    if (ret.firstWhereOrNull((element) =>
            element != null && element.key == O2NativeAppEnum.attendance.key) !=
        null && !AttendanceAssembleControlService.to.closeOldAttendance()) {
      ret.add(AppFrontData(
          name: O2NativeAppEnum.attendanceOld.name,
          key: O2NativeAppEnum.attendanceOld.key,
          type: O2AppTypeEnum.native,
          nativeEnum: O2NativeAppEnum.attendanceOld));
    }
    return ret;
  }

  ///
  /// 门户应用
  ///
  List<AppFrontData?> getCurrentPortalAppList() {
    var list = appStyle?.portalList ?? [];
    return list
        .map<AppFrontData?>((e) {
          String? portalId = e.id;
          String? name = e.name;
          if (portalId == null || name == null) {
            return null;
          }
          AppFrontData data = AppFrontData(
              name: name,
              key: portalId,
              type: O2AppTypeEnum.portal,
              portalId: portalId);
          return data;
        })
        .where((element) => element != null)
        .toList();
  }

  O2NativeAppEnum? _getO2NativeWithKey(String? key) {
    if (key == null) {
      return null;
    }
    switch (key) {
      case "task":
        return O2NativeAppEnum.task;
      case "taskcompleted":
        return O2NativeAppEnum.taskcompleted;
      case "read":
        return O2NativeAppEnum.read;
      case "readcompleted":
        return O2NativeAppEnum.readcompleted;
      case "bbs":
        return O2NativeAppEnum.bbs;
      case "calendar":
        return O2NativeAppEnum.calendar;
      case "cms":
        return O2NativeAppEnum.cms;
      case "meeting":
        return O2NativeAppEnum.meeting;
      case "mindMap":
        return O2NativeAppEnum.mindMap;
      case "attendance":
        return O2NativeAppEnum.attendance;
      case "yunpan":
        return O2NativeAppEnum.yunpan;
      default:
        return null;
    }
  }

  ///
  /// 是否显示系统消息
  ///
  bool isShowSystemMessage() {
    if (appStyle != null) {
      return appStyle?.systemMessageSwitch ?? true;
    }
    return true;
  }

  ///
  /// 简易模式
  ///
  bool isSimpleMode() {
    if (appStyle != null) {
      return appStyle?.simpleMode ?? false;
    }
    return false;
  }

  /// 推广页invoke脚本
  String promotionPageScript() {
    if (appStyle != null) {
      return appStyle?.promotionPageScript ?? '';
    }
    return '';
  }
  
  /// 语音助手invoke脚本
  String speechScript() {
     if (appStyle != null) {
      return appStyle?.speechScript ?? '';
    }
    return '';
  }
  /// 扩展参数
  Map<String, dynamic> extendParam() {
     if (appStyle != null) { 
      return appStyle?.extendParam ?? {};
     }
     return {};
  }

  /// 首页tab 门户 扩展参数
  ExtendParamHomeTabPortal? getExtendParamHomeTabPortal(String key) {
    final p = extendParam();
    if (p[key] != null) {
      return ExtendParamHomeTabPortal.fromJson(p[key]);
    }
    return null;
  }

  /// 首页居中，如果居中页面个数就固定了 5 个。appIndexPages无效了
  bool isIndexCentered() {
    if (appStyle != null) {
      return appStyle?.indexCentered ?? false;
    }
    return false;
  }

  /// 首页信息中心 过滤条件
  List<String> indexFilterCmsCategoryList () {
    return appStyle?.cmsCategoryFilterList ?? [];
  }

  /// 首页办公中心 过滤条件
  List<String> indexFilterProcessList () {
    return appStyle?.processFilterList ?? [];
  }

  /// 首页页面列表
  List<String> appIndexPages() {
    return appStyle?.appIndexPages ?? [];
  }

  ///
  /// 首页是显示门户还是默认的
  ///
  String? homeIndexPage() {
    if (appStyle != null &&
        appStyle?.indexType == 'portal' &&
        appStyle?.indexPortal?.isNotEmpty == true) {
      return appStyle!.indexPortal!;
    }
    return null;
  }

  ///启动 logo图
  Widget aboutLogoImageView() {
    return _commonAppImageView('launch_logo', 48, 48, 'icon_settings_about.png');
  }

  ///启动 logo图
  Widget launchLogoImageView() {
    return _commonAppImageView('launch_logo', 128, 128, 'icon_settings_about.png');
  }

  ///
  ///首页底部Home focus 图
  Widget homeFocusImageView() {
    return _commonAppImageView('index_bottom_menu_logo_focus', 48, 48, 'index_bottom_bar_selected.png');
  }
 
  ///
  ///首页底部Home blur 图
  Widget homeBlurImageView() {
    return _commonAppImageView('index_bottom_menu_logo_blur', 48, 48, 'index_bottom_bar_unselected.png');
  }
   

  ///登录页头像 图
  Widget loginAvatarImageView() {
    return _commonAppImageView('login_avatar', 76, 76, 'login_avatar.png');
  }
  

  /// 应用页面 图片 375
  Widget appPageImageView() {
    return _commonAppImageView('application_top', 375, 195, 'application_top.png');
  }

  ///流程图标 图
  // Uint8List? getProcessDefaultImage() {
  //   return _getServerBase64Image('process_default');
  // }

  ///关于 图
  Widget setupAboutImageView() {
    return _commonAppImageView('setup_about_logo', 22, 22, 'icon_settings_about.png');
  }


  Widget _commonAppImageView(String keyName, double width, double height, String defaultAssetImage) {
    if (appStyle != null && appStyle!.images != null) {
      final element =
          appStyle?.images?.firstWhere((e) => e.name == keyName);
      if (element != null) {
        final webUrl = O2ApiManager.instance.webBaseUrl();
        if (element.path?.isNotEmpty == true && webUrl?.isNotEmpty == true) {
          final url = '$webUrl/${element.path!}';
          return Image.network(
            url,
            width: width,
            height: height,
            fit: BoxFit.fill,
          );
        } else if (element.value?.isNotEmpty == true) {
          return Image.memory(
            base64Decode(element.value!),
           width: width,
            height: height,
            fit: BoxFit.fill,
          );
        }
      }
    }
    return AssetsImageView(
      defaultAssetImage,
      width: width,
            height: height,
            fit: BoxFit.fill,
    );
  }
  
}
